package cn.itzd.service.impl;

import cn.itzd.entity.LoginUser;
import cn.itzd.entity.dto.LoginUserDto;
import cn.itzd.entity.vo.LoginUserVo;
import cn.itzd.service.LoginService;
import cn.itzd.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @Author: dada
 * @Version: 1.0
 * @Description:
 */
@Service
@Slf4j
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtUtils jwtUtils;


    @Override
    public LoginUserVo login(LoginUserDto longinUser) {
        //传入账号和密码
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(longinUser.getUserName(),longinUser.getPassword());
        //调用security中，实现好的UserDetailsService类，说白了就是走到这里，会调用自定义的UserDetailsServiceImpl类中loadUserByUsername方法
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //判断是否认证通过
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("用户名或密码错误");
        }
        //获取userid 生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String jwt = jwtUtils.generatorToken(loginUser);
        loginUser.setPassword("******");
        return new LoginUserVo(jwt,loginUser);
    }
}
